{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4324a245",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import sys  \n",
    "import json\n",
    "import torch \n",
    "import argparse\n",
    "import numpy as np\n",
    "from PIL import Image \n",
    "from tqdm import tqdm \n",
    "from utils import model_gen, load_jsonl\n",
    "from transformers import AutoModelForCausalLM, AutoTokenizer  \n",
    "  \n",
    "ckpt_path = 'internlm/internlm-xcomposer2-vl-7b'\n",
    "tokenizer = AutoTokenizer.from_pretrained(ckpt_path, trust_remote_code=True)\n",
    "model = AutoModelForCausalLM.from_pretrained(ckpt_path, device_map=\"cuda\", trust_remote_code=True).eval().cuda().half()\n",
    "model.tokenizer = tokenizer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "58fd22b8",
   "metadata": {},
   "outputs": [],
   "source": [
    "samples = load_jsonl('./data/ai2d_test.jsonl')\n",
    "image_root = './data/ai2d/'\n",
    "import re\n",
    "pattern = re.compile(r'[A-Z]')\n",
    "\n",
    "results = []\n",
    "for sample in tqdm(samples):\n",
    "    text = sample['text']\n",
    "    image = os.path.join(image_root, sample['image'])\n",
    "    with torch.cuda.amp.autocast():\n",
    "        response = model_gen(model, text, image) \n",
    "    res = pattern.findall(response)\n",
    "    if len(res) == 0:\n",
    "        print('Error:', output_text); res = 'E'\n",
    "    results.append(res[0] == sample['answer'])\n",
    "print (np.mean(results))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9129802d",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
